package com.mxm.app.myapplication.tools;

import org.json.JSONObject;

import java.io.*;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Tools {
    private final static Set<String> PublicSuffixSet = new HashSet<String>(
     Arrays.asList(new String(
             "com|org|net|gov|edu|co|tv|mobi|info|asia|xxx|onion|cn|com.cn|edu.cn|gov.cn|net.cn|org.cn|jp|kr|tw|com.hk|hk|com.hk|org.hk|se|com.se|org.se")
      .split("\\|")));
     private static Pattern IP_PATTERN = Pattern.compile("(\\d{1,3}\\.){3}(\\d{1,3})");

    /**
     * md5加密方法,md5(要加密的信息)
     * @param md5(要加密的信息)
     * @return String
     */
    public static String getMD5(String md5) {
        // 生成一个MD5加密计算摘要
        MessageDigest md;
        try {
            md = MessageDigest.getInstance("MD5");
            // 计算md5函数
            md.update((md5).getBytes());
            // digest()最后确定返回md5 值hash，返回值为8位字符串。因为md5 hash值是16位的hex值，实际上就是8位的字符
            // BigInteger函数则将8位的字符串转换成16位hex值，用字符串来表示；得到字符串形式的hash值
            return new BigInteger(1, md.digest()).toString(16);
        } catch (NoSuchAlgorithmException e) {
            return md5;
        }// MD5 SHA-256...
    }
    /**
     * 截取字符串str中指定字符 strStart、strEnd之间的字符串
     *
     * @param str
     * @param strStart
     * @param strEnd
     * @return
     */
    public static String subString(String str, String strStart, String strEnd) {
        /* 找出指定的2个字符在 该字符串里面的 位置 */
        int strStartIndex = str.indexOf(strStart);
        int strEndIndex = str.indexOf(strEnd);
        /* index 为负数 即表示该字符串中 没有该字符 */
        if (strStartIndex < 0) {
            return "字符串 :---->" + str + "<---- 中不存在 " + strStart + ", 无法截取目标字符串";
        }
        if (strEndIndex < 0) {
            return "字符串 :---->" + str + "<---- 中不存在 " + strEnd + ", 无法截取目标字符串";
        }
        /* 开始截取 */
        String result = str.substring(strStartIndex, strEndIndex).substring(strStart.length());
        return result;
    }
    /*
     * 中文转unicode编码
     */
    public static String gbEncoding(final String gbString) {
        char[] utfBytes = gbString.toCharArray();
        String unicodeBytes = "";
        for (int i = 0; i < utfBytes.length; i++) {
            String hexB = Integer.toHexString(utfBytes[i]);
            if (hexB.length() <= 2) {
                hexB = "00" + hexB;
            }
            unicodeBytes = unicodeBytes + "\\u" + hexB;
        }
        return unicodeBytes;
    }
    /*
     * unicode编码转中文
     */
    public static String decodeUnicode(final String dataStr) {
        int start = 0;
        int end = 0;
        final StringBuffer buffer = new StringBuffer();
        while (start > -1) {
            end = dataStr.indexOf("\\u", start + 2);
            String charStr = "";
            if (end == -1) {
                charStr = dataStr.substring(start + 2, dataStr.length());
            } else {
                charStr = dataStr.substring(start + 2, end);
            }
            char letter = (char) Integer.parseInt(charStr, 16); // 16进制parse整形字符串。
            buffer.append(new Character(letter).toString());
            start = end;
        }
        return buffer.toString();
    }
    //汉字转换成二进制字符串
    public static String strToBinStr(String str) {
        char[] chars=str.toCharArray();
        StringBuffer result = new StringBuffer();
        for(int i=0; i<chars.length; i++) {
            result.append(Integer.toBinaryString(chars[i]));
            result.append(" ");
        }
        return result.toString();
    }
    //二进制字符串转换成汉字
    public static String BinStrTostr(String binary) {
        String[] tempStr=binary.split(" ");
        char[] tempChar=new char[tempStr.length];
        for(int i=0;i<tempStr.length;i++) {
            tempChar[i]=BinstrToChar(tempStr[i]);
        }
        return String.valueOf(tempChar);
    }


    //将二进制字符串转换成int数组
    public static int[] BinstrToIntArray(String binStr) {
        char[] temp=binStr.toCharArray();
        int[] result=new int[temp.length];
        for(int i=0;i<temp.length;i++) {
            result[i]=temp[i]-48;
        }
        return result;
    }

    //将二进制转换成字符
    public static char BinstrToChar(String binStr){
        int[] temp=BinstrToIntArray(binStr);
        int sum=0;
        for(int i=0; i<temp.length;i++){
            sum +=temp[temp.length-1-i]<<i;
        }
        return (char)sum;
    }
    //零宽字加密
    public static String ZeroWidthWrdEncryption(String str){
        char[] chars=gbEncoding(str).toCharArray();
        StringBuffer result = new StringBuffer();
        StringBuffer jtext = new StringBuffer("\\uFEFF");
        for(int i=0; i<chars.length; i++) {
           if(Integer.toBinaryString(chars[i]).length()==7){
               result.append("0");
               result.append(Integer.toBinaryString(chars[i]));
           }else {
               result.append("00");
               result.append(Integer.toBinaryString(chars[i]));
           }
        }
        for(int i=0; i<result.toString().length(); i++) {
            if(i%2==0){
                switch(result.toString().substring(i,i+2)){
                    //\uFEFF
                    case "00" :
                        jtext.append("\\u200a");
                        break;
                    case "01" :
                        jtext.append("\\u200b");
                        break;
                    case "10" :
                        jtext.append("\\u200c");
                        break;
                    case "11" :
                        jtext.append("\\u200d");
                        break;
                }
            }

        }
        jtext.append("\\uFEFF");
//        System.out.println(jtext.toString());
        return decodeUnicode(jtext.toString());
    }
    //零宽字解密
    public static String ZeroWidthWordDecryption(String txt){
        String text = gbEncoding(txt);
        String str = text.substring(text.indexOf("\\ufeff")+6, text.lastIndexOf("\\ufeff"));
        str = str.replace("\\u200a","00");
        str = str.replace("\\u200b","01");
        str = str.replace("\\u200c","10");
        str = str.replace("\\u200d","11");
        char[] tempChar=new char[str.length()/8];
        for(int i=0;i<str.length();i++) {
            if(i%8==0){
//                System.out.println(str.substring(i,i+8));
//                System.out.println(BinstrToChar(str.substring(i,i+8)));
                tempChar[i/8]=BinstrToChar(str.substring(i,i+8));
            }
        }
        return decodeUnicode(String.valueOf(tempChar));
    }
    //零宽字解密
    public static String ZeroWidthWordDecryptionWeb(String txt){
        char[] tempChar =null;
        try {
            String text = gbEncoding(txt);
            text = text.replace("\\u200a", "00");
            text = text.replace("\\u200b", "01");
            text = text.replace("\\u200c", "10");
            text = text.replace("\\u200d", "11");
            tempChar = new char[text.length() / 8];
            for (int i = 0; i < text.length(); i++) {
                if (i % 8 == 0) {
                    tempChar[i / 8] = BinstrToChar(text.substring(i, i + 8));
                }
            }
        }catch (Exception e) {
            return "on";
        }
        return decodeUnicode(String.valueOf(tempChar));
    }

    /**
     * GET网页访问方法
     * urls：要获取网页的链接
     * @param urls
     * @param encoded 为null，默认UTF-8
     * @return
     */
    public static String URL_Get(String urls,String encoded) {
        StringBuffer jg = new StringBuffer();
        try {
            URL url = new URL(urls);
           /* System.out.println("URL 为：" + url.toString());
            System.out.println("协议为：" + url.getProtocol());
            System.out.println("验证信息：" + url.getAuthority());
            System.out.println("文件名及请求参数：" + url.getFile());
            System.out.println("主机名：" + url.getHost());
            System.out.println("路径：" + url.getPath());
            System.out.println("端口：" + url.getPort());
            System.out.println("默认端口：" + url.getDefaultPort());
            System.out.println("请求参数：" + url.getQuery());
            System.out.println("定位位置：" + url.getRef());*/
            HttpURLConnection connection=(HttpURLConnection)url.openConnection();
            //设置请求方式
            connection.setRequestMethod("GET");
            //设置连接超时
            connection.setConnectTimeout(3*1000);
            //设置请求头
            connection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36");
            //获取输入流
            BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
            byte[] b = new byte[1024];
            int len = 0;
            if(null==encoded){
                encoded="UTF-8";
            }
            while((len = bis.read(b)) != -1){
                jg.append(new String(b, 0, len,encoded));
            }
            bis.close();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return jg.toString();
    }
    //文字数量统计
    public static Integer StatisticsWritten(String text){
        char[] t1 = null;
        t1 = text.toCharArray();
        int t0 = t1.length;
        int count = 0;
        for (int i = 0; i < t0; i++) {
            if (Character.toString(t1[i]).matches("[\\u4E00-\\u9FA5]+")) {
                count ++;
            }
        }
        return count;
    }

    public static String getQQByName(String qq){
        String text = URL_Get("https://r.qzone.qq.com/fcg-bin/cgi_get_portrait.fcg?uins="+qq,"gbk");
        String[] texts = text.split(",");
        return texts[6].replace("\"","");
    }
    /**
     * 获取url的顶级域名
     * @param urls
     * @return
     */
    public static String getURLDomainName(String urls) {
        URL url = null;
        try {
            url = new URL(urls);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        String host = url.getHost();
               if (host.endsWith(".")){
                        host = host.substring(0, host.length() - 1);
                  }
              if (IP_PATTERN.matcher(host).matches()){
                        return host;
                   }
               int index = 0;
                String candidate = host;
               for (; index >= 0;) {
                        index = candidate.indexOf('.');
                       String subCandidate = candidate.substring(index + 1);
                       if (PublicSuffixSet.contains(subCandidate)) {
                               return candidate;
                         }
                        candidate = subCandidate;
                    }
              return candidate;
            }
    /**
     * 获取url的主域名
     * @param url
     * @return
     */
    public static String getURLName(String url){
        Pattern p = Pattern.compile("(?<=//|)((\\w)+\\.)+\\w+");
        Matcher m = p.matcher(url);
        if(m.find()){
            return m.group();
        }
        return "获取失败";
    }
    public static byte[] getUTF8BytesFromGBKString(String gbkStr) {
        int n = gbkStr.length();
        byte[] utfBytes = new byte[3 * n];
        int k = 0;
        for (int i = 0; i < n; i++) {
            int m = gbkStr.charAt(i);
            if (m < 128 && m >= 0) {
                utfBytes[k++] = (byte) m;
                continue;
            }
            utfBytes[k++] = (byte) (0xe0 | (m >> 12));
            utfBytes[k++] = (byte) (0x80 | ((m >> 6) & 0x3f));
            utfBytes[k++] = (byte) (0x80 | (m & 0x3f));
        }
        if (k < utfBytes.length) {
            byte[] tmp = new byte[k];
            System.arraycopy(utfBytes, 0, tmp, 0, k);
            return tmp;
        }
        return utfBytes;
    }

    /**
     * <p>
     *     获取系统本项目路径
     *     linux系统返回:项目名路径+/WEB-INF/classes/
     *     window系统war项目返回:项目名路径+\src\main\resources\
     *     window系统jar项目返回:项目名路径
     * </p>
     * @return
     */
    public static String getSystemPath(){
        String filePath=null;
        if("/".equals(File.separator)){//判断系统linux否则win系统
            String classPath = Tools.class.getClassLoader().getResource("/").getPath();
            filePath = classPath.substring(0,classPath.indexOf("/WEB-INF/classes"));
            filePath = filePath.replace("\\", "/");
            filePath = filePath+"/WEB-INF/classes/";
        }else {
            if(new File(System.getProperty("user.dir")+"/src/main").exists()){
                filePath = System.getProperty("user.dir")+"\\src\\main\\resources\\";
            }else {
                filePath = System.getProperty("user.dir");
            }
        }
        return filePath;
    }

    public static void main(String[] args) {
//        System.out.println(getSystemPath());
//        System.out.println(ZeroWidthWordDecryption(""));
//        System.out.println(gbEncoding("漫"));
//        String cat = ZeroWidthWrdEncryption("猫");
//        String zoo = "狗"+cat+"狗";
//        System.out.println("加密后:"+zoo);
//        System.out.println("解密出:"+ZeroWidthWordDecryption(zoo));
//        System.out.println(Getcountry("127.0.0.1"));
//        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
//        System.out.println(df.format(new Date()));// new Date()为获取当前系统时间
//        System.out.println(getQQByName("2535080855"));
//        System.out.println(URL_Get("https://users.qzone.qq.com/fcg-bin/cgi_get_portrait.fcg?uins=2535080855","GBK"));
//        System.out.println(getURLDomainName("https://blog.urusai.me"));
//        System.out.println(getMD5("2535080855"));
//        String s = "http://mc.lxbkw.com/123546";
//        System.out.println(getURLName(s));
//        System.out.println(new Validation().isUrl("http://mc.lxbkw.com"));
//        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
//        Date d = new Date();
//        System.out.println(d);
//        System.out.println(df.format(d));// new Date()为获取当前系统时间
//        System.out.println(UUID.randomUUID().toString());
    }
}
